// utils/wsClient.ts
export class UniWebSocketClient {
    private url: string;
    private userId: string;
    private socketTask: UniApp.SocketTask | null = null;
    private isConnected = false;
    private reconnectDelay = 3000;
    private heartbeatInterval = 10000;
    private heartbeatTimer: any = null;
    private reconnectTimer: any = null;
    private manuallyClosed = false;

    constructor(url: string, userId: string) {
        this.url = url;
        this.userId = userId;
        this.connect();
    }
    private messageCallbacks: Array<(msg: string) => void> = [];

    onMessage(callback: (msg: string) => void) {
        this.messageCallbacks.push(callback);
    }

    private connect() {
        console.log("🔌 正在连接 WebSocket...", this.url);
        this.socketTask = uni.connectSocket({
            url: this.url,
            header: {
                "user-id": this.userId,
            },
            success: () => {
                console.log("✅ 发起 WebSocket 连接成功");
            },
        });

        this.socketTask.onOpen(() => {
            console.log("✅ WebSocket 已连接");
            this.isConnected = true;
            this.startHeartbeat();
        });

        this.socketTask.onMessage((res) => {
            if (res.data === "pong") {
                console.log("💓 收到 pong 心跳响应");
            } else {
                console.log("📩 收到消息:", res.data);
                this.messageCallbacks.forEach(cb => cb(res.data));
            }
        });

        this.socketTask.onClose((e) => {
            console.log(e);
            console.warn("❌ WebSocket 已关闭");
            this.isConnected = false;
            this.stopHeartbeat();
            if (!this.manuallyClosed) {
                this.tryReconnect();
            }
        });

        this.socketTask.onError((err) => {
            console.error("⚠️ WebSocket 错误:", err);
            this.socketTask?.close();
        });
    }

    private startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.isConnected) {
                this.send(`{ "msg": "ping" }`);
            }
        }, this.heartbeatInterval);
    }

    private stopHeartbeat() {
        clearInterval(this.heartbeatTimer);
    }

    private tryReconnect() {
        if (this.reconnectTimer) return;
        console.log(`🔁 ${this.reconnectDelay / 1000} 秒后尝试重连...`);
        this.reconnectTimer = setTimeout(() => {
            this.reconnectTimer = null;
            this.connect();
        }, this.reconnectDelay);
    }

    send(msg: any) {
        console.log(msg, "消息体");
        if (this.isConnected && this.socketTask) {
            this.socketTask.send({
                data: msg,
                fail: (err) => {
                    console.warn("🚫 发送失败:", err);
                },
            });
        } else {
            console.warn("⛔ WebSocket 未连接，消息未发送");
        }
    }

    close() {
        this.manuallyClosed = true;
        this.stopHeartbeat();
        this.socketTask?.close();
    }
}
